<?php
/**
 * @author Feng
 * @date 2012-6-16
 */

class collection_collect_http {
	private $adapter = null;
	private $cookiejar = null;
	private $_isResonseOk = false;
	
	public function __construct() {
		$this->setAdapter();
	}
	
	public function setAdapter($adapter = null) {
		if(null == $adapter) {
			$this->adapter = curl_init();
			curl_setopt($this->adapter, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($this->adapter, CURLOPT_SSL_VERIFYPEER, false);
		} else {
			$this->adapter = $adapter;
		}
	}
	
	public function getAdapter() {
		return $this->adapter;
	}
	
	public function setCookieJar() {
		$this->_isResonseOk = false;
		if($this->cookiejar == null) {
			$this->cookiejar = tempnam(_DIRECTORY_VAR . '/tmp', 'SUP');
		}
		curl_setopt($this->getAdapter(), CURLOPT_COOKIEFILE, $this->cookiejar);
		curl_setopt($this->getAdapter(), CURLOPT_COOKIEJAR, $this->cookiejar);
	}
	
	public function cleanCookieJar() {
		@unlink($this->cookiejar);
	}
	
	public function get($url, $returnHeader = true) {
		curl_setopt($this->getAdapter(), CURLOPT_URL, $url);
		curl_setopt($this->getAdapter(), CURLOPT_POST, false);
		$this->setCookieJar();
		curl_setopt($this->getAdapter(), CURLOPT_HEADER, $returnHeader);
		$response = curl_exec($this->getAdapter());
		if($returnHeader) {
			$this->_isResonseOk = preg_match('/200 OK/is', $response);
		} else {
			$this->_isResonseOk = true;
		}
		$this->parameters = array();
		return $response;
	}
	
	public function post($url, $parameters, $returnHeader = true) {
		curl_setopt($this->getAdapter(), CURLOPT_URL, $url);
		curl_setopt($this->getAdapter(), CURLOPT_POST, true);
		$this->setCookieJar();
		curl_setopt($this->getAdapter(), CURLOPT_POSTFIELDS, $parameters);
		curl_setopt($this->getAdapter(), CURLOPT_HEADER, $returnHeader);
		$response = curl_exec($this->getAdapter());
		if($returnHeader) {
			$this->_isResonseOk = preg_match('/200 OK/is', $response);
		} else {
			$this->_isResonseOk = true;
		}
		$this->parameters = array();
		return $response;
	}
	
	public function getIsOk() {
		return $this->_isResonseOk;
	}

}
